package com.vspush.tcp.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class Service {

	public static void main(String[] args) {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap sps = new ServerBootstrap();
			sps.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
			sps.childHandler(new ChannelInitializer<NioSocketChannel>() {
				@Override
				protected void initChannel(NioSocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){

						@Override
						public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
							ByteBuf in = ((ByteBuf) msg);
							StringBuffer sb = new StringBuffer();
						        while (in.isReadable()) {
						        	@SuppressWarnings("resource")
									ByteBufInputStream bbis = new ByteBufInputStream(in);
						        	String str = bbis.readLine();
						        	sb.append(str+"\r\n");
						        	if(str.length()==0){
						        		break;
						        	}
						        }
						    System.out.println(sb.toString());
						    ReferenceCountUtil.release(msg);
						    ctx.writeAndFlush(Unpooled.copiedBuffer("this is a test", CharsetUtil.UTF_8));
							ctx.close();
						}
						 @Override
						    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
						        cause.printStackTrace();
						        ctx.close();
						    }
						
					});
				}
			});
			ChannelFuture f= sps.bind(9636).sync();
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

}
